package com.xzkydz.sign;

import com.xzkydz.root.AllTaskRequestEntity;
import com.xzkydz.root.SubmissionEntity;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class CheckSign {

    /**
     * 服务端可以调用此方法检查sign是否正确
     *
     * @param object 必须是 {@link AllTaskRequestEntity}  或者 {@link SubmissionEntity}
     * @return
     */
    public static boolean isOk(Object object){
        try{
            String sign = "";
            if (object instanceof AllTaskRequestEntity) {
                sign = buildSign("xzkydz", getPars(object));
                AllTaskRequestEntity entity = (AllTaskRequestEntity) object;
                return sign.equals(entity.getSign()) ? true : false;
            } else if (object instanceof SubmissionEntity) {
                sign = buildSign("xzkydz", getPars(object));
                SubmissionEntity entity = (SubmissionEntity) object;
                return sign.equals(entity.getSign()) ? true : false;
            } else {
                return false;
            }
        }catch (UnsupportedEncodingException e){
            return  false;
        } catch (NullPointerException e){
            return  false;
        }
    }

    /**
     * app端生成签名
     *
     * @param object 必须是 {@link AllTaskRequestEntity}  或者 {@link SubmissionEntity}
     * @return
     */
    public static void setSign(Object object)  {
        try {
            if ((object instanceof AllTaskRequestEntity) || (object instanceof SubmissionEntity)) {
                String sign = buildSign("xzkydz", getPars(object));
                if (object instanceof  AllTaskRequestEntity){
                    ((AllTaskRequestEntity) object).setSign(sign);
                }else {
                    ((SubmissionEntity) object).setSign(sign);
                }
            }
        }catch (UnsupportedEncodingException e){

        }catch (NullPointerException e){

        }
    }


    //获取参数集合
    private static Map<String, String> getPars(Object object) {
        Map<String, String> signMap = new HashMap<String, String>();  //签名map去除sign
        if (object instanceof AllTaskRequestEntity) {
            AllTaskRequestEntity entity = (AllTaskRequestEntity) object;
            signMap.put("bglx", entity.getBglx());
            signMap.put("device", entity.getDevice());
            signMap.put("zhjr", entity.getZhjr());
        } else {
            SubmissionEntity entity = (SubmissionEntity) object;
            Map<String, String> taskMap = new HashMap<String, String>();  //taskinfo
            signMap.put("device", entity.getDevice());
            signMap.put("method", entity.getMethod());
            signMap.put("project", entity.getProject());
            taskMap.put("taskid", entity.getTaskinfo().getTaskid()); //服务端分配的任务id'
            taskMap.put("shjdw", entity.getTaskinfo().getShjdw()); //受检单位
            taskMap.put("shbbh", entity.getTaskinfo().getShbbh()); //设备编号
            taskMap.put("jcry", entity.getTaskinfo().getJcry()); //测试人员
            taskMap.put("date", entity.getTaskinfo().getDate()); //测试时间
            signMap.putAll(taskMap);
        }
        return signMap;
    }

    public static String buildSign(String auCode, Map<String, String> params) throws UnsupportedEncodingException {
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        StringBuilder sbr = new StringBuilder();
        sbr.append(auCode);
        for (String key : keys) {
            String value = params.get(key);
            if (isNotEmpty(key) && isNotEmpty(value)) {
                sbr.append(key).append(value);
                // 注意这里：将所有参数值转换为UTF-8编码，然后拼装，并作URL ENCODING
            }
        }
        return MD5Upper32(sbr.toString());
    }

    public static String MD5Upper32(String origin) throws UnsupportedEncodingException {
        String charsetName = "UTF-8";
        String key = "0123456789ABCDEF";
        String resultString = null;
        String[] hexDigits = new String[key.length()];
        for (int i = 0; i < key.length(); i++) {
            hexDigits[i] = String.valueOf(key.charAt(i));
        }
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetName)), hexDigits);
        } catch (Exception ex) {

        }
        return resultString;
    }

    /**
     * @param b 字节数组
     * @return 16进制字串
     */
    private static String byteArrayToHexString(byte[] b, String[] hexDigits) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i], hexDigits));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b, String[] hexDigits) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    private static boolean isNotEmpty(String str) {
        return (str != null && str.length() != 0) ? true : false;
    }

}
